<?php namespace App\Foundation\Access;

use App\Repositories\User\UserRepositoryInterface;

class AccessUser
{
    protected $user_id;

    protected $user;

    protected $token;

    /**
     * 检查是否登陆
     *
     * @return bool
     */
    public function check()
    {
        return !is_null($this->user());
    }

    /**
     * 获取登录用户
     *
     * @return \App\Models\User
     */
    public function user()
    {
        if (!$this->user) {
            $this->user = $this->getUser();
        }

        return $this->user;
    }

    /**
     * 设置用户id
     *
     * @param $user_id
     *
     * @return int
     */
    public function setUserId($user_id)
    {
        $this->user_id = (int)$user_id;
    }

    public function id()
    {
        return $this->getUserId();
    }

    public function getUserId()
    {
        return $this->user_id;
    }

    public function setToken($token)
    {
        $this->token = $token;
    }

    /**
     * 获取用户
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function getUser()
    {
        if ($this->user_id <= 0) {
            return null;
        }

        /** @var UserRepositoryInterface $service */
        $service = app(UserRepositoryInterface::class);

        return $service->show($this->user_id);
    }

}
